const bcrypt = require("bcryptjs");
const { getUserInfo } = require("../service/user.service");

const {
  userFormateError,
  userAlreadyExited,
  userRegisterError,
  invalidPassword,
} = require("../constant/err.type");

//验证器
const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  //合理性
  if (!user_name || !password) {
    console.error("用户名或者密码为空", ctx.request.body);
    ctx.app.emit("error", userFormateError, ctx);
    return;
  }
  await next();
};

const verifyUser = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  //合法性
  // if (await getUserInfo({ user_name })) {
  //   console.error("用户已存在",ctx.request.body);
  //   ctx.app.emit("error", userAlreadyExited, ctx);
  //   return;
  // }

  try {
    const res = await getUserInfo({ user_name });
    if (res) {
      console.error("用户已存在", { user_name });
      ctx.app.emit("error", userAlreadyExited, ctx);
      return;
    }
  } catch (err) {
    console.error("获取用户信息错误", err);
    ctx.app.emit("error", userRegisterError, ctx);
    return;
  }

  await next();
};

const cryptPaasword = async (ctx, next) => {
  const { password } = ctx.request.body; //拿到密码
  const salt = bcrypt.genSaltSync(10); //加密算法
  const hash = bcrypt.hashSync(password, salt); //将密码与算好的  结合在一起
  ctx.request.body.password = hash; //返回加密后的密码
  await next();
};

const verifyLogin = async (ctx, next) => {
  //1.判断这个用户是否存在(不存在，我们就报错)
  const { user_name, password } = ctx.request.body;
  try {
    const res = await getUserInfo({ user_name });
    if (!res) {
      console.error("用户名不存在", user_name);
      ctx.app.emit("error", userDoesNotExist, ctx);
      return;
    }
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit("error", invalidPassword, ctx);
      return
    }
  } catch (err) {
    console.error(err);
    ctx.app.emit("error", userLoginError, ctx);
  }

  //2.密码是否匹配(不匹配就报错)
  await next();
};




module.exports = {
  userValidator,
  verifyUser,
  cryptPaasword,
  verifyLogin,
};
